package com.aghcampusnavigation.navi;

/**
 * Created by Basia on 28.04.14.
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.io.File;
import java.util.ArrayList;

import android.os.Build.VERSION;
import	android.util.Log;

    public class SQLliteDatabaseHelper extends SQLiteOpenHelper {



            //The Android's default system path of your application database.
           private String DB_PATH ;//= "/data/data/com.aghcampusnavigation.navi/databases/";

            private static String DB_NAME = "db.sqlite";

            private SQLiteDatabase myDataBase;

            private final Context myContext;

            private static final String TABLE_BUILDINGS = "buildings";

            private static final String KEY_ID = "_id";
            private static final String NUMBER="name";
            private static final String LATITUDE="latitude";
            private static final String LONGITUDE="longitude";
            private static final String DESCRIPTION="description";
            private static final String COUNT ="count";

            private static final String[] COLUMNS = {KEY_ID,NUMBER, LATITUDE, LONGITUDE,DESCRIPTION, COUNT};




            /**
             * Constructor
             * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
             * @param context
             */


            public SQLliteDatabaseHelper(Context context) {

                super(context, DB_NAME, null, 1);
                this.myContext = context;
                if(android.os.Build.VERSION.SDK_INT >= 4.2){
                    DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
                }
                else
                {
                    DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
                }
            }


        /**
         * Creates a empty database on the system and rewrites it with your own database.
         * */
        public void createDataBase() throws IOException{

            boolean dbExist = checkDataBase();

            if(dbExist){
                //do nothing - database already exist
            }else{

                //By calling this method and empty database will be created into the default system path
                //of your application so we are gonna be able to overwrite that database with our database.
                this.getReadableDatabase();

                try {

                    copyDataBase();

                } catch (IOException e) {

                    throw new Error("Error copying database");

                }
            }

        }

        /**
         * Check if the database already exist to avoid re-copying the file each time you open the application.
         * @return true if it exists, false if it doesn't
         */
        private boolean checkDataBase(){

            boolean checkDB = false;

            try{
                String myPath = DB_PATH + DB_NAME;
                File dbfile = new File(myPath);
                //checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
                checkDB = dbfile.exists();

            }catch(SQLiteException e){

                //database does't exist yet.

            }



            return checkDB;
        }

        /**
         * Copies your database from your local assets-folder to the just created empty database in the
         * system folder, from where it can be accessed and handled.
         * This is done by transfering bytestream.
         * */
        private void copyDataBase() throws IOException{

            //Open your local db as the input stream
            InputStream myInput = myContext.getAssets().open(DB_NAME);

            // Path to the just created empty db
            String outFileName = DB_PATH + DB_NAME;

            //Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer))>0){
                myOutput.write(buffer, 0, length);
            }

            //Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();

        }

        public void openDataBase() throws SQLException{

            //Open the database
            String myPath = DB_PATH + DB_NAME;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }

        @Override
        public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

        }

        @Override
        public void onCreate(SQLiteDatabase db) {

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }

        public DataOfBuilding getBuilding(int id){

            // 1. get reference to readable DB
            //SQLiteDatabase db = this.getReadableDatabase();

            // 2. build query
            Cursor cursor =
                    myDataBase.query(TABLE_BUILDINGS, // a. table
                            COLUMNS, // b. column names
                            KEY_ID +" = ?", // c. selections
                            new String[] { String.valueOf(id) }, // d. selections args
                            null, // e. group by
                            null, // f. having
                            null, // g. order by
                            null); // h. limit

            DataOfBuilding building = new DataOfBuilding();
            // 3. if we got results get the first one
            try {
                cursor.moveToFirst();

                // 4. build building object
                building.settingID(Integer.parseInt(cursor.getString(0)));
                building.settingNumber(cursor.getString(1));
                building.settingLatitude(Float.parseFloat(cursor.getString(2)));
                building.settingLongitude(Float.parseFloat(cursor.getString(3)));
                building.settingDescription(cursor.getString(4));
                building.settingCount(Integer.parseInt(cursor.getString(5)));
            } catch (Exception e) {
                Log.e("Database cursor error", e.getMessage());
                building = new DataOfBuilding(999, "ERROR", (float)19.0, (float)50.0, "ERROR");
            } finally {
                cursor.close();
            }

            //log
            Log.d("getBuilding("+id+")", building.toString());

            // 5. return building
            return building;
        }

        public DataOfBuilding[] getFavorites(){

            // 1. get reference to readable DB
            //SQLiteDatabase db = this.getReadableDatabase();

            Log.d("FAV", "starting");
            // 2. build query
            Cursor cursor =
                    myDataBase.query(TABLE_BUILDINGS, // a. table
                            COLUMNS, // b. column names
                            COUNT + " > ?", // c. selections
                            new String[]{ "0" }, // d. selections args
                            null, // e. group by
                            null, // f. having
                            COUNT + " DESC", // g. order by
                            null); // h. limit

            // 3. if we got results get the first one
            DataOfBuilding building;
            ArrayList<DataOfBuilding> buildingArrayList =new ArrayList<DataOfBuilding>();
            try {
                cursor.moveToFirst();
                Log.d("FAV", "getting fav first");
                do {
                    Log.d("FAV", "getting next fav");
                    building = new DataOfBuilding();
                    building.settingID(Integer.parseInt(cursor.getString(0)));
                    building.settingNumber(cursor.getString(1));
                    building.settingLatitude(Float.parseFloat(cursor.getString(2)));
                    building.settingLongitude(Float.parseFloat(cursor.getString(3)));
                    building.settingDescription(cursor.getString(4));
                    building.settingCount(Integer.parseInt(cursor.getString(5)));

                    buildingArrayList.add(building);
                } while (cursor.moveToNext());

            } catch (Exception e) {
                Log.e("Database cursor error", e.getMessage());
            } finally {
                cursor.close();
            }

            //log
            Log.d("getFavorites()", buildingArrayList.toString());

            // 5. return building
            return buildingArrayList.toArray(new DataOfBuilding[buildingArrayList.size()]);
        }

        public void addCount(DataOfBuilding building){
            //for logging
            Log.d("addbuilding", building.toString());

            // 1. get reference to writable DB
            SQLiteDatabase db = this.getWritableDatabase();

            // 2. create ContentValues to add key "column"/value
            ContentValues values = new ContentValues();
            values.put(COUNT, building.gettingCount()+1);
            db.update(TABLE_BUILDINGS, values, "_id=" + building.gettingID(), null);


            // 4. close
            db.close();
        }

    }